import math
import os
import uuid

import cv2
import numpy as np
from PIL import Image, ImageFont, ImageDraw


def imageMax(folders):
    test_length = 480
    test_height = 48

    maxLength = 0
    maxHeigh = 0

    maxLengthFile = 0
    maxHeighFile = 0
    for folder in folders:
        files = [f for f in os.listdir(folder)]
        for filename in files:
            path = folder + '/' + filename
            img = Image.open(path)
            imgSize = img.size  # 图片的长和宽
            maxSize = max(imgSize)  # 图片的长边
            minSize = min(imgSize)  # 图片的短边
            # if maxSize > test_length:
            #     print(path)
            # if minSize > test_height:
            #     print(path)
            if maxSize <= test_length and minSize <= test_height:
                print(path)
            if maxSize > maxLength:
                maxLength = maxSize
                maxLengthFile = path
            if minSize > maxHeigh:
                maxHeigh = minSize
                maxHeighFile = path
    return maxLength, maxHeigh, maxLengthFile, maxHeighFile


#

root = 'D:/workspace/python/train_data/'


def config():
    with open(root + "train_data_configs/words/生僻字.txt", 'r', encoding='utf-8') as f:
        word = f.readlines()
    word_dict_length = len(word)  # 字库字数
    fontPath = root + "train_data_configs/fonts/chn/chinese_cht.ttf"  # 黑体
    save_dir = root + "/train_data_spz"
    min_words_length = 9
    max_words_length = 13
    img_count = 1000
    return word, fontPath, save_dir, min_words_length, max_words_length, img_count


def draw_to_image(size, fontPath, font_size, text, save_dir, file_name):
    background = np.ones(size) * 255
    font = ImageFont.truetype(fontPath, font_size)
    img = Image.fromarray(background)
    draw = ImageDraw.Draw(img)
    draw.text((1, 1), text, font=font, fill='black')
    img = np.array(img)
    # out_path = os.path.join(save_dir, file_name)
    out_path = save_dir + "/" + file_name
    # out_path = "images/" + file_name
    # 'images/423aa84a-461b-414f-9742-23cc2ead2d00.jpg'
    cv2.imwrite(out_path, img)


def generate_words(word, count, length_range_min, length_range_max):
    line_words_list = []
    line_words = ""
    globe_word_dict_index = 0
    for k in range(count + 1):
        bit_length = np.random.randint(length_range_min, length_range_max)
        for i in range(bit_length + 1):
            try:
                line_words = line_words + word[globe_word_dict_index].split("\n")[0]
            except:
                globe_word_dict_index = 0
                line_words = line_words + word[globe_word_dict_index].split("\n")[0]
            globe_word_dict_index += 1
        line_words_list.append(line_words)
        line_words = ""
    return line_words_list


def genImage():
    word, fontPath, save_dir, min_words_length, max_words_length, img_count = config()
    line_words_list = generate_words(word, img_count, min_words_length, max_words_length)
    for line in line_words_list:
        length = len(line)
        font_size = 33 if np.random.randint(0, 2) == 0 else 20
        file_name = str(uuid.uuid4()) + ".jpg"
        if (font_size == 33):
            size = (42, math.ceil(length * 34.4))
            draw_to_image(size, fontPath, font_size, line, save_dir, file_name)
        else:
            size = (29, math.ceil(length * 20.8))
            draw_to_image(size, fontPath, font_size, line, save_dir, file_name)
        with open("label.txt", "a") as f:
            f.write("images/" + file_name + "/t" + line + "\n")


# root = 'D:/workspace/python/train_data/train_data_configs/fonts/chn/'
# msyh_font = root + "msyh.ttc"
# simfang_font = root + "simfang.ttc"
# simsun_font = root + "simsun.ttc"
#

#
# draw_to_image(size, msyh_font, font_size, line, 'D:/workspace/python/train_data/Ling/demo/test/', 'test.jpg')

# (4430, 2448, 'D:/ocr/ocr_resouces/icdar2017rctw_train_v1.2/train/image_162-09.jpg',
# 'D:/ocr/ocr_resouces/icdar2017rctw_train_v1.2/train/image_1460-20.jpg')
# result = imageMax(['D:/ocr/ocr_resouces/icdar2017rctw_train_v1.2/train'])
# print(result)
# (818, 62, 'D:/ocr/ocr_resouces/中文文档文字识别/Chinese_dataset/images/img_0720567.jpg'
# , 'D:/ocr/ocr_resouces/中文文档文字识别/Chinese_dataset/images/img_0224598.jpg')
# result = imageMax(['D:/ocr/ocr_resouces/中文文档文字识别/Chinese_dataset/images'])
# print(result)
# result = imageMax(['D:/ocr/ocr_resouces/train_data/train_data_customer/crop_img'])
# print(result)

line = '中文文档文字识别'
length = len(line)
size = (42, math.ceil(length * 34.4))
draw_to_image(size, 'D:/ocr/ocr_resources/reader/fonts2/方正北魏楷书_gbk.ttf', 33, line,
              'D:/workspace/python/train_data/Ling/demo/test/', 'test.jpg')
